<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/6 09:56
 */

namespace module\ai\front\form;

use module\ai\enum\KeyStatusEnum;
use module\ai\library\channel\Factory;
use mof\front\Form;
use mof\Model;

class KeyForm extends Form
{
    protected array $validate = [
        'param' => [
            'config/a', 'flag', 'project', 'status/d', 'remark',
        ],
        'rule'  => [
            'config|密钥信息' => 'require|array',
            'status|状态'     => 'require|in:-1,0,1',
        ],
    ];

    protected function elements(Model $model = null): array
    {
        $keyInstance = Factory::key($model->flag);
        if ($url = $keyInstance->getRegUrl()) {
            $regUrl = [
                "label"   => "入口",
                "type"    => "html",
                "content" => '<a href="' . $url . '" target="_blank">点击这里注册/登录</a>',
            ];
        }
        if ($useProject = $keyInstance->getUseProject()) {
            $project = [
                "label"   => "项目",
                "prop"    => "project",
                "value"   => $model['project'] ?? '',
                "type"    => "input",
                "options" => $useProject,
                "intro"   => "填写项目名称。",
            ];
        }
        $result = [
            $regUrl ?? null,
            [
                "label"    => "平台",
                "prop"     => "flag",
                "value"    => $model['flag'],
                "type"     => "select",
                "options"  => Factory::platformDict()->toElementData()->toSelectOptions(),
                "disabled" => true
            ],
            $project ?? null,
            ...$this->getConfigElements($keyInstance, $model->config ?? []),
            [
                "label" => "备注",
                "prop"  => "remark",
                "value" => $model['remark'] ?? '',
            ],
            [
                "label"   => "状态",
                "prop"    => "status",
                "value"   => (int)($model['status'] ?? 1),
                "type"    => "select",
                "options" => KeyStatusEnum::toDict()->toElementData()->toSelectOptions(),
                "rule"    => [
                    "required" => true,
                ]
            ]
        ];

        return array_values(array_filter($result));
    }

    protected function getConfigElements($keyInstance, $config = []): array
    {
        return $keyInstance->getKeysForm($config);
    }
}